﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPF_AutoMapping_Demo
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class ClassRoom
    {
        public string ClassName { get; set; }
        public List<Student> Students { get; set; } = new List<Student>();
    }

    public class StudentDto
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class ClassRoomDto
    {
        public string ClassName { get; set; }
        public Collection<StudentDto> StudentDtos { get; set; } = new Collection<StudentDto>();
    }

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Student, StudentDto>();
            CreateMap<ClassRoom, ClassRoomDto>()
                .ForMember(dest => dest.StudentDtos, opt => opt.MapFrom(src => new Collection<StudentDto>(src.Students.Select(s => new StudentDto
                {
                    Name = s.Name,
                    Age = s.Age
                }).ToList())));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 配置 AutoMapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<MappingProfile>();
            });

            var mapper = config.CreateMapper();

            // 创建源对象
            var classRoom = new ClassRoom
            {
                ClassName = "Math 101",
                Students = new List<Student>
            {
                new Student { Name = "Alice", Age = 20 },
                new Student { Name = "Bob", Age = 22 }
            }
            };

            // 执行映射
            var classRoomDto = mapper.Map<ClassRoomDto>(classRoom);

            // 输出结果
            Console.WriteLine($"Class Name: {classRoomDto.ClassName}");
            foreach (var studentDto in classRoomDto.StudentDtos)
            {
                Console.WriteLine($"Student Name: {studentDto.Name}, Age: {studentDto.Age}");
            }
            Console.ReadLine();
        }
    }
}
